import time
import threading

from PySide6.QtCore import QObject, Signal
from playwright.sync_api import sync_playwright
import os
import platform
import sys


def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.dirname(os.path.abspath(__file__)), relative_path)

class Screenshot(QObject):
    log_signal = Signal(str)

    def __init__(self, username, password, login_url):
        super().__init__()
        self.username = username
        self.password = password
        self.login_url = login_url
        self.append_log("Screenshot 实例已创建")

        # 使用线程局部存储，解决多线程问题
        self.local = threading.local()


    def append_log(self, message):
        self.log_signal.emit(message)

    def _initialize_playwright(self):
        """线程局部初始化 Playwright 实例"""
        if hasattr(self.local, 'initialized') and self.local.initialized:
            return

        self.local.lock = threading.Lock()
        with self.local.lock:
            try:
                self.local.playwright = sync_playwright().start()

                args = [
                    "--disable-gpu",
                    "--no-sandbox",
                    "--window-size=1920,1080",
                    "--ignore-certificate-errors",
                    "--disable-dev-shm-usage",
                    "--disable-extensions",
                    "--blink-settings=imagesEnabled=false",
                    "--disable-software-rasterizer"
                ]
                playwright_dir = resource_path('ms-playwright')  # 👈 使用这个函数
                self.append_log(f"playwright_dir:{playwright_dir}")
 
                # 查找实际的chromium版本
                chromium_path = None
                for root, dirs, files in os.walk(playwright_dir):
                    if 'chrome.exe' in files or 'chrome' in files:
                        chromium_path = os.path.join(root, 'chrome.exe' if platform.system() == 'Windows' else 'chrome')
                        break
                
                if not chromium_path:
                    self.append_log(f"在{playwright_dir}中找不到chromium可执行文件")
                    raise FileNotFoundError("找不到Chromium可执行文件")
                
                self.append_log(f"使用的chromium可执行文件路径: {chromium_path}")
                
                self.local.browser = self.local.playwright.chromium.launch(executable_path=chromium_path, headless=True, args=args, handle_sigint=False, handle_sigterm=False)
                self.local.context = self.local.browser.new_context()
                self.local.page = self.local.context.new_page()

                self.append_log(f"[线程 {threading.get_ident()}] 浏览器初始化完成")
                self.local.initialized = True
            except Exception as e:
                self.append_log(f"初始化失败: {e}")

    def init_driver(self):
        """公共初始化入口"""
        self._initialize_playwright()

    def screen(self, target_url, save_path):
        """主截图流程，包含登录逻辑"""
        self._initialize_playwright()
        page = getattr(self.local, 'page', None)

        if not page:
            self.append_log("页面对象未初始化")
            return False

        try:
            page.goto(target_url)

            current_url = page.url
            if "sign_in" in current_url or "login" in current_url:
                self.append_log("当前页面是登录页面，开始登录")

                # 等待 standard_tab 出现并点击
                try:
                    page.wait_for_selector('[data-qa-selector="standard_tab"]', timeout=10000)
                    page.click('[data-qa-selector="standard_tab"]')
                except:
                    pass

                # 填写用户名和密码
                page.wait_for_selector('#user_login', state='visible', timeout=10000)
                page.fill('#user_login', self.username)

                page.wait_for_selector('#user_password', state='visible', timeout=10000)
                page.fill('#user_password', self.password)

                self.append_log("表单填写完成，提交登录")

                # 提交登录按钮
                submit_button = page.query_selector('button[type="submit"]') or \
                                page.query_selector('input[type="submit"]')

                if submit_button:
                    submit_button.click()
                else:
                    self.append_log("未找到登录按钮")

                return self.capture(save_path)
            else:
                page.goto(target_url)
                return self.capture(save_path)

        except Exception as e:
            self.append_log(f"截图过程中发生错误: {str(e)}")
            return False

    def capture(self, save_path):
        """等待目标元素并截图"""
        page = getattr(self.local, 'page', None)
        if not page:
            self.append_log("页面对象未初始化")
            return False

        try:
            # 等待目标表格加载完成
            page.wait_for_selector("//table[contains(@class, 'tree-table')]", timeout=10000)
            time.sleep(1)  # 可选等待渲染

            page.screenshot(path=save_path)

            self.append_log(f"截屏已保存到: {save_path}")
            return True
        except Exception as e:
            self.append_log(f"截屏失败: {str(e)}")
            return False

    def close(self):
        """释放所有资源"""
        if not hasattr(self.local, 'initialized') or not self.local.initialized:
            return

        with self.local.lock:
            try:
                if hasattr(self.local, 'page'):
                    self.local.page.close()
                if hasattr(self.local, 'context'):
                    self.local.context.close()
                if hasattr(self.local, 'browser'):
                    self.local.browser.close()
                if hasattr(self.local, 'playwright'):
                    self.local.playwright.stop()

                self.append_log(f"[线程 {threading.get_ident()}] 浏览器资源已释放")
            except Exception as e:
                self.append_log(f"释放资源失败: {str(e)}")